<template>
    <div class="Right">
       <div class="breadcrumb">
            <!-- 面包屑 -->
            <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">Home</el-breadcrumb-item>
            <el-breadcrumb-item>UserManagement</el-breadcrumb-item>
            <el-breadcrumb-item>RightList</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
      <!-- 通过v-model获取到搜索的数据 -->
        <div class="fl seach">
            <el-input placeholder="Please enter the content" v-model="searchVal" class="search-input" @keydown.enter.native="handleSearch"  @input="handleData">
                <!-- 点击搜索按钮执行搜索的方法，将获取回来的数据赋值给tableData -->
                <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
            </el-input>
            <el-button type="primary" plain @click="handleAdd">Add</el-button>
        </div>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%">

      <el-table-column
        type="index"
        width="60">
      </el-table-column>
      <el-table-column
        prop="permissionName"
        label="PermissionName"
        width="240">
      </el-table-column>
      
      <el-table-column
        prop="privilegeLevel"
        label="level"
        width="220">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.level==='0'">{{scope.row.level}}</el-tag>
            <el-tag v-else-if="scope.row.level==='1'" type="success">{{scope.row.level}}</el-tag>
            <el-tag v-else type="warning">{{scope.row.level}}</el-tag>
          </template>
      </el-table-column>

      <el-table-column
        label="Operation">
        <template slot-scope="scope">
          <!-- 点击编辑按钮 -->
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            size="mini">Edit</el-button>
            <!-- scope.row获取到的是你点击的那一行对象的所有数据 -->
          <el-button
            icon="el-icon-delete"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">Delete</el-button>
          
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加用户对话框 -->
    <el-dialog title="AddRight" :visible.sync="AddDialogVisible" width="40%" height="40%" class="addDialog">
      <!-- 在el-form组件上添加rules属性 -->
      <el-form :model="addForm" ref="addRef" :rules="myrules">
        <el-form-item label="RightName" label-width="110px" prop="permissionName">
          <el-input v-model="addForm.permissionName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="Level" label-width="110px" prop="level">
           <el-select v-model="levelVal" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item._id"
              :label="item.level"
              :value="item.level">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="btn">
        <el-button @click="AddDialogVisible = false" >Cancel</el-button>
        <el-button type="primary" @click="confirmAdd" >Confirm</el-button>
      </div>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog title="EditorRight" :visible.sync="EditDialogVisible" width="40%" height="40%" class="addDialog">
      <!-- 在el-form组件上添加rules属性 -->
      <el-form :model="editForm" ref="editRef" :rules="myrules">
        <el-form-item label="RightName" label-width="100px" prop="permissionName">
          <el-input v-model="editForm.permissionName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="Level" label-width="100px" prop="level">
           <el-select v-model="editForm.level" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item._id"
              :label="item.level"
              :value="item.level">
            </el-option>
          </el-select>
        </el-form-item>
       
      </el-form>
      <div slot="footer" class="btn">
        <el-button @click="EditDialogVisible = false" >Cancel</el-button>
        <el-button type="primary" @click="confirmEdit" >Confirm</el-button>
      </div>
    </el-dialog>

    <!-- 分页器 -->
     <el-pagination
        background
        @current-change="handleCurrentChange"
        layout="prev, pager, next"
        :total="totalNum"
        :current-page="currentPage"
        :page-size="pageSize">
      </el-pagination>
    </div>
</template>
<script>
import {Meteor} from 'meteor/meteor';
import { AccountsServer} from 'meteor/accounts-base'
import {Right} from '/imports/collections/collection'

export default {
    data () {
        return {
            searchVal:'' ,     //搜索的数据
            editData:{},
            tableData:[],          //表格中的数据,
            totalNum:0,     //数据总条数，默认为0
            currentPage:1,    //默认展示第一页
            pageSize:6 ,       //页面显示的数据条数
            pageNum:1 ,        //当前页码默认为1
            addForm:{
              permissionName:'',
             },
            editForm:{
                permissionName:'',
                level:''
             },
            myrules: {                    //对表单进行校验
                permissionName: [
                { required: true, message: 'Please input a username', trigger: 'blur' }
                ]
            }, 
            AddDialogVisible:false ,     //添加对话框的默认状态
            EditDialogVisible:false,      //编辑对话框的默认状态
            levelVal:'',
            options:[]
        }
    },
    created () {
      var that=this;
      var timeout=setTimeout(function(){
            that.initList();
        },700)
    },
    // 层级过滤
    filters: {
      filterLevel (level) {
        if (level === '0') {
          return '一级'
        } else if (level === '1') {
          return '二级'
        } else {
          return '三级'
        }
      }
    },
    methods: {
        handleData(){
          this.initList();
        },
        // 搜索用户
        handleSearch(){
          this.pageNum=1;
          var id=[];
          for(var i=0;i<Right.find().count();i++){
            if(Right.find().fetch()[i].permissionName.indexOf(this.searchVal.trim())!=-1){
              id.push(Right.find().fetch()[i]._id)
            }
          }
          var newTableData=[]
        // 循环找出要查找的对象
          for(var i=0;i<this.tableData.length;i++){
              for(var j=0;j<id.length;j++){
                if(this.tableData[i]._id===id[j]){
                  newTableData.push(this.tableData[i])
                }
              }
          }
          this.tableData=[]
          // console.log(newTableData)
          for(var j=0;j<newTableData.length;j++){
              this.tableData.push(newTableData[j]);
          }
        },                                                                   
        // 添加权限按钮
        handleAdd(){
            this.AddDialogVisible=true;
            this.options=[
              {
              level:"一级"
            },{
              level:"二级"
            },{
              level:"三级"
            }
            ];
            this.levelVal='';
            this.$nextTick(() => {
            // 对表单进行重置并移除所有的校验结果
                this.$refs.addRef.resetFields();
            })
        },
        // 确认添加操作
        confirmAdd(){
          this.AddDialogVisible=false;
          this.AddDialogVisible=false;
          // 校验通过
          this.$refs.addRef.validate(isPass=>{
            if(isPass){
              // 添加操作
              if(this.levelVal==='一级'){
                this.levelVal='0';
              }else if(this.levelVal==='二级'){
                this.levelVal='1';
              }else{
                this.levelVal='2';
              }
              var addRight={
                'permissionName':this.addForm.permissionName,
                'level':this.levelVal
              }
              Right.insert(addRight)
              if(this.pageNum>1){
                this.handleCurrentChange(this.pageNum)
              }else{
                this.initList();
              }
              // console.log(this.pageNum+"当前页码数")
            }
          })
        },
        // 点击编辑按钮
        handleEdit(row){
            // console.log(row)
            this.options=[
              {
              level:"一级"
            },{
              level:"二级"
            },{
              level:"三级"
            }
            ]
            this.EditDialogVisible=true;
            this.editForm.level=row.level;
            this.editForm.permissionName=row.permissionName;
            this.editForm._id=row._id;
            this.editData._id=row._id;
            
  
        },
        // 编辑对话框中的确定按钮
        confirmEdit(){
          this.EditDialogVisible=false;
          var id=this.editData._id;
           if(this.editForm.level==='一级'){
                this.editForm.levelVal='0';
              }else if(this.editForm.level==='二级'){
                this.editForm.levelVal='1';
              }else{
                this.editForm.levelVal='2';
              }
          var editRight={
          'permissionName':this.editForm.permissionName,
          'level':this.editForm.levelVal
          }
          Right.update({_id:id},editRight);
          // console.log("options:"+this.options)

          this.initList();
        },
        // 点击删除按钮
        handleDelete(row){
          // console.log(row.id)
          this.$confirm('This action will permanently delete the permission. Do you want to continue?', 'Tips', {
            confirmButtonText: 'Confirm',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }).then(() => {
            // this.tableData.splice(row,1);
            // UserList.remove({'_id':row._id});
            // 删除用户
           Right.remove({_id:row._id});
            // console.log("删除成功后:"+Right.find().fetch());
            if(this.pageNum>1){
                this.handleCurrentChange(this.pageNum)
              }else{
                this.initList();
              }
            this.$message({
              type: 'success',
              message: 'Successful deletion!'
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: 'Canceled deletion'
            });          
          });
        },
        handleCurrentChange(val) {
          // console.log(`当前页: ${val}`);
          // this.tableData=[]
          this.pageNum=val;
          // var UserListData=UserList.find().fetch();
          var UserListData=Right.find().fetch();
          // console.log("this.options:"+JSON.stringify(this.options))
          if(val!==1){
              // 13-(val-1)*6  (val-1)*6+1  2:7 13 | 3:13  18 |  4: 19 20
              for(var i=(val-1)*this.pageSize;i<(val*this.pageSize) && (UserListData.length);i++){
                  this.tableData.push(UserListData[i])
                  this.options.push(UserListData[i])
              }
              if((val*this.pageSize)>UserListData.length){
                  this.tableData=[];
                  this.options=[];
                  for(var i=(val-1)*this.pageSize;i<(UserListData.length);i++){
                  this.tableData.push(UserListData[i])
                   this.options.push(UserListData[i])
                }
              }
              this.changeLevel();
          }else if(val==1){
            this.initList();
          }
        },
        // 层级的转换
        changeLevel(){
          for(var i=0;i<this.options.length;i++){
            if(this.options[i].level==='0'){
              this.options[i].level="一级";
            }else if(this.options[i].level==='1'){
              this.options[i].level='二级';
            }else{
              this.options[i].level='三级';
            }
          }
        },
        
        
        // 表格数据初始化
        initList(){
         
            this.tableData=[];
            this.options=[];
            this.totalNum=Right.find().count();
            var RightData=Right.find().fetch();
            for(var i=0;i<RightData.length;i++){
              if(i<this.pageSize){
                this.tableData.push(RightData[i])
                this.options.push(RightData[i]) 
              }
            }
            // console.log("this.options:"+JSON.stringify(this.options))

            this.changeLevel();
            
          //  Right.insert({
          //    permissionName:'test',
          //    level:'2 '
          //  })
          //  console.log("options:"+this.options)
          
        }
        
      
    }
  }
</script>
<style lang="scss">
    .Right{
       .el-table__header tr,
        .el-table__header th {
          padding: 0;
          height: 70px;
          line-height: 70px;
          color: #333;
      }
      .el-table__body tr,
      .el-table__body td {
          padding: 0;
          height: 50px;
      }
    }
    .search-input {
    width: 300px;
    margin-right: 20px;
    }
    .seach{
        height: 80px;
        line-height: 80px;
    }
    .Right{
        .breadcrumb{
            background-color: #fff;
            height:30px;
        }
        .el-breadcrumb{
        line-height: 30px;
        font-size: 14px;
        padding-left: 10px;
        }   
    }
    .el-pagination {
        margin-top: 20px;
    }
    .addDialog{
        .el-dialog{
          line-height: 0;
        }
        .el-dialog__header{
            height: 100px;
        }
        .el-dialog__body{
            margin-top: -60px;
        }
        .el-dialog__wrapper .el-dialog .el-dialog__footer{
            margin-top: -40px;
            height: 100px;
        }
        .btn{
        margin-top: -20px;
        }
    }
    .Right .el-table__body tr, .Right .el-table__body td{
      line-height: 30px;
     padding-left: 20px;
    }
</style>

